package com.ljp.serializer;

import java.io.*;

/**
 * 基于JDK的序列化器
 * <p>
 * ClassName: JdkSerializer
 * Package: com.ljp.serializer
 * Description:
 *
 * @Author: ljp
 * @Create: 2025/6/4-下午 03:26
 * @Version: 1.0
 */
public class JdkSerializer implements Serializer {
    /**
     * 序列化
     *
     * @param object 序列化对象
     * @return 序列化后的字节数组
     * @throws IOException 序列化异常
     */
    @Override
    public <T> byte[] serialize(T object) throws IOException {
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream);
        objectOutputStream.writeObject(object);
        objectOutputStream.close();
        return byteArrayOutputStream.toByteArray();
    }

    /**
     * 反序列化
     *
     * @param bytes 序列化后的字节数组
     * @param type  反序列化类型
     * @return 反序列化后的对象
     * @throws IOException 反序列化异常
     */
    @Override
    public <T> T deserialize(byte[] bytes, Class<T> type) throws IOException {
        ByteArrayInputStream inputStream = new ByteArrayInputStream(bytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(inputStream);
        try {
            return (T) objectInputStream.readObject();
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        } finally {
            objectInputStream.close();
        }
    }
}
